package cn.edu.scau.liangshanhero.configurateUtf8Filter;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.jface.dialogs.MessageDialog;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class WebXMLConfigureUTF8FilterByDOM {
	static Document doc;

	public static void UpdateWebXMLUTF8(File webXMLFile) {
		// 添加显示对话框
		MessageDialog.openInformation(null, "UpdateWebXMLUTF8",
				webXMLFile.toString());
		// Logger log=new Logger(null, null);
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
			doc = dbBuilder.parse(webXMLFile);
			doc.normalize();
			Element root = doc.getDocumentElement();
			MessageDialog.openInformation(null, "UpdateWebXMLUTF8 root",
					root.toString());
			Boolean isEncodingFilterConfiged = false;

			if (doc != null) {
			// 打印出节点的所有值 printNode(root);
			}

			// 查找encoding节点，如果没有，就添加，如果有，就不添加
			NodeList filters = root.getElementsByTagName("filter-name");
			MessageDialog.openInformation(null, "UpdateWebXMLUTF8 root",
					filters.toString());
			for (int i = 0; i < filters.getLength(); i++) {
				System.out.println("已经配置好的过滤器名称是：  "
						+ filters.item(i).getTextContent());
				if (filters.item(i).getTextContent().equals("encoding")) {
					System.out.println("现在判断是否相等  "
							+ filters.item(i).getTextContent()
									.equals("encoding"));
					isEncodingFilterConfiged = true;
					break;
				}

			}
			// 如果没有配置，就开始配置

			if (isEncodingFilterConfiged == false) {
				insertUTF8FilterConfigureInformation(root, webXMLFile);
				isEncodingFilterConfiged = true;
			} else
				System.out.println("已经配置好了过滤器，不需要 再配置...");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private static void insertUTF8FilterConfigureInformation(Element root,
			File webXMLFile) throws Exception {

		Element filter = doc.createElement("filter");
		Element filterName = doc.createElement("filter-name");
		// 和前面一样，但是因为filter和filter-mapping都有filter名，在生产邪门了文档时，前面的追加无效
		Element filterMappingFilterName = doc.createElement("filter-name");

		Element filterClass = doc.createElement("filter-class");
		Element initParam = doc.createElement("init-param");
		Element paramName = doc.createElement("param-name");
		Element paramValue = doc.createElement("param-value");
		Element filterMapping = doc.createElement("filter-mapping");
		Element urlPattern = doc.createElement("url-pattern");

		Text filterNameText = doc.createTextNode("encoding");
		Text filterMappingFilterNameText = doc.createTextNode("encoding");
		Text filterClassText = doc
				.createTextNode("org.springframework.web.filter.CharacterEncodingFilter");
		Text paramNameText = doc.createTextNode("encoding");
		Text paramValueText = doc.createTextNode("UTF-8");
		Text urlPatternText = doc.createTextNode("/*");
		// 叶节点赋值
		filterName.appendChild(filterNameText);
		filterMappingFilterName.appendChild(filterMappingFilterNameText);

		filterClass.appendChild(filterClassText);
		paramName.appendChild(paramNameText);
		paramValue.appendChild(paramValueText);
		urlPattern.appendChild(urlPatternText);

		// 非叶结点由子节点组合（添加）
		initParam.appendChild(paramName);
		initParam.appendChild(paramValue);
		// filter添加filte-name, filter-class, init-param

		filter.appendChild(filterName);

		filter.appendChild(filterClass);
		filter.appendChild(initParam);
		// //filter-mapping添加filter-name, url-pattern
		filterMapping.appendChild(filterMappingFilterName);
		filterMapping.appendChild(urlPattern);

		// 添加过滤器filter和filter-mapping

		// 在最后添加
		// root.appendChild(filter);
		// root.appendChild(filterMapping);

		// 在其他地方添加，如果有了过滤器，就在所有的过滤器之前添加，
		// 针对的是现有的web.xml一定有了filter，所以，只在现有的过滤器之前添加
		// 奇怪：添加顺序的时候，filterMapping在前，filter在后交换顺序也不行
		root.insertBefore(filter, doc.getElementsByTagName("filter").item(0));
		root.insertBefore(filterMapping,
				doc.getElementsByTagName("filter-mapping").item(0));

		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(webXMLFile);
		transformer.transform(source, result);

	}

	public static void printNode(Element element) {
		int k;
		NamedNodeMap attr;
		NodeList children = element.getChildNodes();

		attr = element.getAttributes();
		int r = children.getLength();
		if (attr != null) {
			System.out.print(element.getNodeName());
			for (int j = 0; j < attr.getLength(); j++) {
				System.out.print(attr.item(j).getNodeName() + "="
						+ attr.item(j).getNodeValue());
			}

		} else if (attr == null) {
			System.out.print(element.getNodeName());
		}

		if (element.hasChildNodes()) {
			for (k = 0; k < r; k++) {
				if (children.item(k).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
					printNode((Element) children.item(k));
				} else if (children.item(k).getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
					System.out.println(children.item(k).getNodeValue());
				}
			}
		}

	}
}